import React, { useState, useEffect, useRef } from 'react';
import axios from '../../axios';
import { Button, Form, Input, Toast, Dialog, NavBar, Radio, Selector, DatePicker, Space, ImageUploader, ImageUploadItem } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import styles from './Xiu.module.css';
import { PictureOutline, CameraOutline } from 'antd-mobile-icons';

interface UserInfo {
  userName?: string;
  img?: string;
  phone?: string;
  sex?: string;
  age?: number;
  money?: number;
  vip?: number;
}

export default function Xiu() {
  const navigate = useNavigate();
  const [userInfo, setUserInfo] = useState<UserInfo>({});
  const [isEditing, setIsEditing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [uploadLoading, setUploadLoading] = useState(false);
  const [form] = Form.useForm();
  const id = localStorage.getItem('user');
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    fetchUserInfo();
  }, []);

  const fetchUserInfo = async () => {
    try {
      setLoading(true);
      const res = await axios.get(`/index?id=${id}`);
      setUserInfo(res.data.data);
      form.setFieldsValue({
        userName: res.data.data.userName,
        phone: res.data.data.phone,
        sex: res.data.data.sex,
        age: res.data.data.age
      });
      setLoading(false);
    } catch (error) {
      console.error('获取用户信息失败', error);
      Toast.show({
        icon: 'fail',
        content: '获取用户信息失败',
      });
      setLoading(false);
    }
  };

  const handleSave = async (values: UserInfo) => {
    try {
      setLoading(true);
      const res = await axios.post('/updateUser', {
        id,
        ...values
      });
      
      if (res.data.code === 200) {
        Toast.show({
          icon: 'success',
          content: '信息更新成功',
        });
        setIsEditing(false);
        fetchUserInfo(); // 重新获取更新后的信息
      } else {
        Toast.show({
          icon: 'fail',
          content: res.data.message || '更新失败',
        });
      }
      setLoading(false);
    } catch (error) {
      console.error('更新用户信息失败', error);
      Toast.show({
        icon: 'fail',
        content: '更新用户信息失败',
      });
      setLoading(false);
    }
  };

  const confirmLogout = () => {
    Dialog.confirm({
      content: '确定要退出登录吗？',
      onConfirm: () => {
        localStorage.removeItem('user');
        navigate('/login');
      },
    });
  };

  const uploadAvatar = async (file: File) => {
    try {
      setUploadLoading(true);
      
      const formData = new FormData();
      formData.append('avatar', file);
      formData.append('userId', id || '');
      
      const res = await axios.post('/uploadAvatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      if (res.data.code === 200) {
        Toast.show({
          icon: 'success',
          content: '头像上传成功',
        });
        
        // 更新用户信息
        setUserInfo({
          ...userInfo,
          img: res.data.data.avatarUrl
        });
      } else {
        Toast.show({
          icon: 'fail',
          content: res.data.message || '上传失败',
        });
      }
      
      setUploadLoading(false);
    } catch (error) {
      console.error('上传头像失败', error);
      Toast.show({
        icon: 'fail',
        content: '上传头像失败',
      });
      setUploadLoading(false);
    }
  };

  const handleAvatarClick = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      uploadAvatar(file);
    }
  };

  return (
    <div className={styles.xiuContainer}>
      <NavBar onBack={() => navigate(-1)}>个人信息</NavBar>
      
      <div className={styles.avatarSection}>
        <div 
          className={styles.avatarWrapper}
          onClick={handleAvatarClick}
        >
          <img 
            src={userInfo.img || 'https://via.placeholder.com/150'} 
            alt="头像" 
            className={styles.avatar} 
          />
          {uploadLoading && (
            <div className={styles.avatarLoading}>
              <span>上传中...</span>
            </div>
          )}
          <div className={styles.avatarEditOverlay}>
            <CameraOutline fontSize={24} color="#fff" />
          </div>
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            style={{ display: 'none' }}
            onChange={handleFileChange}
          />
        </div>
      </div>

      {!isEditing ? (
        <div className={styles.infoSection}>
          <div className={styles.infoItem}>
            <span className={styles.label}>用户名</span>
            <span className={styles.value}>{userInfo.userName}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>手机号</span>
            <span className={styles.value}>{userInfo.phone || '未设置'}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>性别</span>
            <span className={styles.value}>{userInfo.sex || '未设置'}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>年龄</span>
            <span className={styles.value}>{userInfo.age || '未设置'}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>洋币余额</span>
            <span className={styles.value}>{userInfo.money || 0}</span>
          </div>
          
          <div className={styles.buttonGroup}>
            <Button 
              block 
              color='primary' 
              onClick={() => setIsEditing(true)}
              style={{ marginBottom: '12px' }}
            >
              编辑信息
            </Button>
            
            <Button 
              block 
              color='danger' 
              onClick={confirmLogout}
            >
              退出登录
            </Button>
          </div>
        </div>
      ) : (
        <div className={styles.formSection}>
          <Form
            form={form}
            layout='horizontal'
            footer={
              <div className={styles.formButtons}>
                <Button block onClick={() => setIsEditing(false)}>
                  取消
                </Button>
                <Button 
                  block 
                  type='submit' 
                  color='primary'
                  loading={loading}
                >
                  保存
                </Button>
              </div>
            }
            onFinish={handleSave}
          >
            <Form.Item 
              name='userName' 
              label='用户名'
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input placeholder='请输入用户名' />
            </Form.Item>
            
            <Form.Item 
              name='phone' 
              label='手机号'
              rules={[
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
              ]}
            >
              <Input placeholder='请输入手机号' />
            </Form.Item>
            
            <Form.Item name='sex' label='性别'>
              <Radio.Group>
                <Space>
                  <Radio value='男'>男</Radio>
                  <Radio value='女'>女</Radio>
                </Space>
              </Radio.Group>
            </Form.Item>
            
            <Form.Item name='age' label='年龄'>
              <Input type='number' placeholder='请输入年龄' />
            </Form.Item>
          </Form>
        </div>
      )}
    </div>
  );
}
